<template>
  <KView class="sys-search-goods">
    <KView class="search-goods-header clearfix">
      <KView class="page-header-back" @click="backClick">
        <sys-svg name="arrowLeft"></sys-svg>
      </KView>
      <KView class="search-goods-input">
        <search-input v-model="searchValue" placeholder="输入关键字搜索" @change="toSearchData"></search-input>
      </KView>
    </KView>

    <KView class="search-goods-content" v-if="isShow">
      <template v-if="mode==='search'">
        <KView class="search-goods-hot" v-if="hotSearchList.length>0">
          <KView class="search-goods-title">
            <span>热搜榜</span>
          </KView>
          <KView class="search-goods-record">
            <KView v-for="hotSearch in hotSearchList" :key="`hotSearch_${hotSearch.id}`" @click="searchClick(hotSearch)">
              <span :class="hotSearch.type">{{hotSearch.text}}</span>
            </KView>
          </KView>
        </KView>
        <KView class="search-goods-history">
          <KView class="search-goods-title">
            <span>历史记录</span>
            <KView v-if="historyRecordList.length>0" class="search-goods-history-clear" @click="clearHistory">
              <sys-svg name="remove" color="#9b9b9b"></sys-svg>
              <KView class="search-goods-history-clear-text">清空</KView>
            </KView>
          </KView>
          <KView class="search-goods-record">
            <KView v-for="history in historyRecordList" :key="`history_${history.id}`" @click="searchClick(history)">
              <span>{{history.text}}</span>
            </KView>
          </KView>
        </KView>
      </template>
      <template v-else>
        <KView class="search-goods-data">
          <KView class="search-goods-title">
            <span>搜索结果</span>
          </KView>
          <KView class="search-goods-line"></KView>
          <KView class="search-goods-list" v-if="shopGoodsList.length>0">
            <goods-view :goods-list="shopGoodsList" :buy-record="buyRecord" :pagination="pagination" :next-data-fun="toSearchGoods"
              @item-click="itemClick">
            </goods-view>
          </KView>
          <KView v-else class="search-goods-nodata flex-central">
            <KView>
              <KView class="search-goods-nodata-img">
                <img class="sys-img" :src="noDataImg" mode="aspectFit">
              </KView>
              <KView class="search-goods-nodata-text">没有搜索到相关内容</KView>
            </KView>
          </KView>
        </KView>

        <KView class="search-goods-balance" v-if="hasBalance">
          <shop-goods-balance :buy-record="buyRecord"></shop-goods-balance>
        </KView>
      </template>
    </KView>
  </KView>
</template>

<script>
  import GlobalData from 'utils/globalData';
  import SystemUtil from 'utils/systemUtil';

  import SearchGoodsApi from 'services/searchGoodsApi';

  import SearchInput from 'common/searchInput';
  import SysSvg from 'common/sysSvg';
  import GoodsView from 'views/classify/goodsView';
  import ShopGoodsBalance from 'views/classify/goodsView/shopGoodsBalance';

  import Pagination from 'models/pagination';
  import GoodsBuyRecord from 'models/classify/goodsBuyRecord';

  export default {
    computed: {
      hasBalance() {
        let buyRecord = this.buyRecord;
        if (buyRecord === null) {
          return false;
        }

        let goodsModelIds = buyRecord.goodsModelIds;
        return goodsModelIds.length > 0;
      }
    },

    data() {
      return {
        isMiniprogram: process.env.isMiniprogram,
        noDataImg: GlobalData.images.searchGoods.noData,
        isShow: false,
        params: this.getParams(),
        searchValue: '',
        mode: 'search',
        hotSearchList: [],
        historyRecordList: [],
        pagination: null,
        shopGoodsList: [],
        buyRecord: null
      };
    },

    created() {
      this.setSearchLabelList().then(() => {
        this.isShow = true;
      });
    },

    methods: {
      getParams() {
        let query = this.$route.query;
        let params = {};
        let branchId = query.branchId;
        if (branchId !== undefined) {
          params.branchId = Number(branchId);
        }

        let partnerId = query.partnerId;
        if (partnerId !== undefined) {
          params.partnerId = Number(partnerId);
        }
        return params;
      },

      setSearchLabelList() {
        SystemUtil.showLoading('');
        return SearchGoodsApi.getSearchLabelList().then(res => {
          this.hotSearchList = res.hotSearchList;
          this.historyRecordList = res.historyRecordList;
          this.mode = 'search';
          this.shopGoods = null;
          this.buyRecord = null;
          SystemUtil.hideLoading();
          return res;
        }).catch((error) => {
          SystemUtil.hideLoading();
          return null;
        });
      },

      backClick() {
        if (!this.isMiniprogram) {
          window.history.back();
          return;
        }
        wx.navigateBack();
      },

      toSearchData() {
        let searchValue = this.searchValue;
        if (searchValue === '') {
          this.setSearchLabelList();
          return;
        }

        this.pagination = new Pagination();
        SystemUtil.showLoading('');
        this.toSearchGoods(true).then(() => {
          this.mode = 'table';
          this.buyRecord = new GoodsBuyRecord();
          SystemUtil.hideLoading();
        }).catch(() => {
          SystemUtil.hideLoading();
        });
      },

      toSearchGoods(isInit = false) {
        return SearchGoodsApi.getSearchGoods(this.searchValue, this.pagination, this.params).then(shopGoodsList => {
          if (isInit) {
            this.shopGoodsList = shopGoodsList;
          } else {
            this.shopGoodsList.push(...shopGoodsList);
          }
          return shopGoodsList;
        });
      },

      searchClick(data) {
        let text = data.text;
        if (this.searchValue === text) {
          return;
        }

        this.searchValue = text;
        this.toSearchData();
      },

      clearHistory() {
        SystemUtil.showLoading('清空历史记录');
        SearchGoodsApi.clearHistory().then(msg => {
          this.historyRecordList = [];
          SystemUtil.hideLoading();
        }).catch(() => {
          SystemUtil.hideLoading();
        });
      },

      itemClick(goods) {
        let defId = goods.defId;
        if (SystemUtil.isEmpty(defId)) {
          return;
        }

        let url = `/goodsDetail/${defId}`;
        if (this.isMiniprogram) {
          let pages = getCurrentPages();
          if (pages.length <= 2) {
            this.$emit('to-page', url);
            return;
          }

          let page = pages[pages.length - 2];
          let pageName = page.window.pageName;
          if (pageName === 'shopMall') {
            page.window.actionData = {
              type: 'toPage',
              data: {
                url: url
              }
            };
            wx.navigateBack();
          }
        } else {
          this.$router.push({
            path: `/goodsDetail/${defId}`
          });
        }
      }
    },

    components: {
      SearchInput,
      SysSvg,
      GoodsView,
      ShopGoodsBalance
    }
  };

</script>

<style lang="scss">
  .sys-search-goods {
    height: 100%;
    display: flex;
    flex-direction: column;

    .search-goods-header {
      padding: formatPx(20) formatPx(30);
      height: formatPx(70);
      border-bottom: 1px solid #DADADA;

      >div {
        float: left;
        height: 100%;
      }

      .page-header-back {
        width: formatPx(36);
      }

      .search-goods-input {
        width: calc(100% - #{formatPx(72)});
        margin-left: formatPx(36);
        font-size: formatPx(30);
      }
    }

    .search-goods-title {
      border-left: formatPx(10) solid #59C264;
      font-size: formatPx(36);
      padding-left: formatPx(15);
      line-height: formatPx(40);
      height: formatPx(40);
    }

    .search-goods-record {
      margin-top: formatPx(25);
      display: flex;
      flex-wrap: wrap;

      >div {
        margin-right: formatPx(30);
        margin-bottom: formatPx(25);
        height: formatPx(40);
        line-height: formatPx(40);
        padding: formatPx(10) formatPx(15);
        background: #f5f5f5;
        color: #666666;
        font-size: formatPx(26);
        border-radius: 6px;

        .hot-first {
          color: #f80000;
        }

        .hot-second {
          color: #f86300;
        }

        .hot-third {
          color: #f8b500;
        }
      }
    }

    .search-goods-content {
      flex: 1;
      overflow: auto;
      margin-top: formatPx(40);
      margin-bottom: formatPx(20);
      min-height: 0;
      position: relative;

      .search-goods-hot {
        padding-left: formatPx(30);
        margin-bottom: formatPx(40);
      }

      .search-goods-data {
        height: 100%;

        .search-goods-title {
          margin: 0 formatPx(30);
          margin-bottom: formatPx(40);
        }

        .search-goods-line {
          margin: 0 formatPx(30);
          height: 1px;
          background: #DADADA;
        }

        .search-goods-list {
          margin-top: formatPx(45);
          height: calc(100% - #{formatPx(145)} - 1px);
          overflow: auto;
        }
      }

      .search-goods-history {
        padding-left: formatPx(30);
        padding-right: formatPx(30);

        .search-goods-history-clear {
          float: right;
          height: 100%;
          font-weight: normal;

          >div {
            float: left;
            height: 100%;
          }

          .sys-svg {
            width: formatPx(38);
          }

          .search-goods-history-clear-text {
            color: #9b9b9b;
            font-size: formatPx(26);
            line-height: formatPx(57);
            margin-left: formatPx(10);
          }
        }
      }

      .search-goods-balance {
        position: absolute;
        left: formatPx(30);
        right: formatPx(30);
        bottom: 0;
        height: formatPx(98);
      }
    }

    .search-goods-nodata {
      height: calc(100% - #{formatPx(100)} - 1px);

      >div {
        width: formatPx(284);
      }

      .search-goods-nodata-img {
        width: 100%;
        height: formatPx(274);
      }

      .search-goods-nodata-text {
        margin-top: formatPx(30);
        color: #666666;
        font-size: formatPx(26);
        text-align: center;
      }
    }
  }

</style>
